<?php

namespace app\common\model;

use app\common\model\BaseModel;
use fast\Tree;


class DepartmentBasic extends BaseModel
{
    // 表名
    protected $name = 'department_basic';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [];


    public function getStatusList()
    {
        return ['normal' =>'正常', 'trash' => '停用','deleted'=>'已删除'];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function tree(){
        $ruleList = self::where(['status'=>'normal'])->order('id', 'asc')->select()->toArray();

        Tree::instance()->init($ruleList);
        $tree = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0),'name',false);

        return $tree;
    }

    public function treeData(){
        $tree = $this->tree();

        $ruleData = [0 =>'无上级'];
        foreach ($tree as $k => &$v) {
            $ruleData[$v['id']] = $v['name'];
        }
        return $ruleData;
    }
    public function getTreeList($selected = [])
    {

        $ruleList = $this->tree();

        $hasChildrens = [];
        foreach ($ruleList as $k => $v) {
            if ($v['haschild']) {
                $hasChildrens[] = $v['id'];
            }
        }

        $nodeList=[];
        foreach ($ruleList as $k => $v) {
            $state = ['selected' => in_array($v['id'], $selected) && ! in_array($v['id'], $hasChildrens)];
            $nodeList[] = [
                'id'     => $v['id'],
                'parent' => $v['pid'] ? $v['pid'] : '#',
                'text'   => __($v['name']),
                'type'   => 'menu',
                'state'  => $state,
            ];
        }

        return $nodeList;
    }
}
